package com.taptech.doufu.util;

/**
 * author zhangyongcun
 * 16/12/13
 */

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.bean.appupdate.ApkInfo;
import com.taptech.doufu.bean.appupdate.UpdateInfo;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.ui.dialog.DialogUpdateApk;
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import rx.Observer;

import static com.taptech.doufu.util.SharedPreferenceUtil.getInt;


/**
 * author zhangyongcun
 * 16/11/7
 * apk 更新工具类
 */

public class UpdateUtil {
    private static final String UPDATEPROMPTCOUNT = "update_prompt_count";
    private static final String UPDATEPROMPTTIME = "update_prompt_time";
    private static final String UPDATEPROMPVERSIONCODE = "update_prompt_version_code";


    public static void userCheckUpdate(Context mContext) {
        getUpdateInfoByServer(mContext,true);
    }



    /**
     * 请求更新的参数
     * @param mContext
     * @return
     */
    public static ApkInfo getApkInfo(Context mContext) {
        try {
            ApkInfo apkInfo = new ApkInfo();
            PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            apkInfo.setApk_version_code(packageInfo.versionCode);
            apkInfo.setApk_version_name(packageInfo.versionName);
            apkInfo.setSdk_version(Build.VERSION.SDK_INT);
            apkInfo.setBuild_mode(Build.MODEL);
            apkInfo.setUser_id(AccountService.getInstance().getUserUid());
            return apkInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 是否为 wifi 连接 1
     */
    public static void isWifiConnect(Context mContext) {
        ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi.isConnected()) {
            getUpdateInfoByServer(mContext,false);
        }
    }

    /**
     * 获取服务器版本信息 2
     *
     * @return
     */
    public static void getUpdateInfoByServer(final Context mContext, final boolean isUserCheck) {
        ApiClient cpApi = new ApiClient();
        cpApi.init(mContext);
        ApkInfo apkInfo = getApkInfo(mContext);
        cpApi.getService().getUpdateInfo(apkInfo.getApk_version_name(),
                apkInfo.getApk_version_code(),
                apkInfo.getUser_id(),
                apkInfo.getBuild_mode(),
                apkInfo.getSdk_version())
                .compose(RxJavaHelper.<UpdateInfo>observeOnMainThread())
                .subscribe(new Observer<UpdateInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        try {
                            DoufuUtils.netWorkErrorToast(mContext);
                        } catch (Exception e1) {

                        }
                    }

                    @Override
                    public void onNext(UpdateInfo updateInfo) {
                        if (updateInfo.getData().isUpdate_is_need()) {
                            if (isUserCheck) {
                                CheckResult res = checkInstall(mContext, updateInfo.getData().getUpdate_info());
                                if (res == CheckResult.INSTALL_FROM_WEB) {
                                    showDialogUpdate(mContext, updateInfo.getData().getUpdate_info());
                                } else if (res == CheckResult.INSTALL_FROM_LOCAL) {
                                    String filePath = Environment.getExternalStorageDirectory()  + "/doufu/doufu.apk";
                                    File apkFile = new File(filePath);
                                    installApp(mContext,apkFile);
                                }else{
                                    Toast.makeText(mContext,"已经是最新版本", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                dealUpdateInfoByServer(mContext, updateInfo.getData().getUpdate_info());
                            }
                        }else if (isUserCheck) {
                            Toast.makeText(mContext,"已经是最新版本", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

        return;
    }

    enum CheckResult{
        INSTALL_FROM_WEB,   //从服务器下载
        INSTALL_FROM_LOCAL, //已经下载在本地的apk
        NEWEST              //已经是最新版本
    }

    public static CheckResult checkInstall(Context mContext,UpdateInfo.DataBean.UpdateInfoBean updateInfoBean) {
        String filePath = Environment.getExternalStorageDirectory()  + "/doufu/doufu.apk";
        File apkFile = new File(filePath);
        if (apkFile.exists()) {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
            if (Integer.parseInt(updateInfoBean.getUpdate_version_code()) > packageInfo.versionCode) {
                return CheckResult.INSTALL_FROM_WEB;
            }else{
                if (packageInfo.versionCode > PackageUtils.getVersionCode(mContext)) {
                    return CheckResult.INSTALL_FROM_LOCAL;
                }else{
                    return CheckResult.NEWEST;
                }
            }
        }else{
            return CheckResult.INSTALL_FROM_WEB;
        }
    }


    /**
     * 处理服务器返回的版本信息
     */
    public static void dealUpdateInfoByServer(Context mContext, UpdateInfo.DataBean.UpdateInfoBean updateInfoBean) {
        CheckResult res = checkInstall(mContext,updateInfoBean);
        if (updateInfoBean.getUpdate_type().equals("0") && checkIsShowDialog(mContext, updateInfoBean)) {//选择更新
            if (res == CheckResult.INSTALL_FROM_WEB) {
                showDialogUpdate(mContext, updateInfoBean);
            } else if (res == CheckResult.INSTALL_FROM_LOCAL) {
                showDialogInstall(mContext);
            }
        } else if (updateInfoBean.getUpdate_type().equals("1")) {//强制更新
            if (res == CheckResult.INSTALL_FROM_WEB) {
                showDialogUpdate(mContext, updateInfoBean);
            } else if (res == CheckResult.INSTALL_FROM_LOCAL) {
                showDialogInstall(mContext);
            }
        } else {
            //其他更新情况
        }
    }

    private static void showDialogInstall(final Context mContext) {
        DoubleBtnTiptDialog doubleBtnLongTextDialog = new DoubleBtnTiptDialog(mContext,
                R.style.updateDialog, "有新的版本可以更新，赶紧试试吧~","当前更新无需下载任何内容", "立即更新",
                new DoubleBtnTiptDialog.CallBack() {
                    @Override
                    public void onBack() {
                        String filePath = Environment.getExternalStorageDirectory()  + "/doufu/doufu.apk";
                        File apkFile = new File(filePath);
                        installApp(mContext,apkFile);
                    }
                });
        doubleBtnLongTextDialog.show();
    }

    /**
     * 检查是否需要显示更新提示
     *
     * @return
     */
    public static boolean checkIsShowDialog(Context mContext, UpdateInfo.DataBean.UpdateInfoBean updateInfoBean) {
        boolean isNeedDialog = false;
        int lastDialogVersionCode = SharedPreferenceUtil.getInt(mContext, UPDATEPROMPVERSIONCODE, getApkInfo(mContext).getApk_version_code());
        if (lastDialogVersionCode == Integer.valueOf(updateInfoBean.getUpdate_version_code())) {//同一版本
            isNeedDialog = isPromptByUser(mContext);
        } else {//新的版本
            initPromptInfo(mContext);
            isNeedDialog = true;
        }
        if (isNeedDialog) {
            updatePromptTime(mContext);
            SharedPreferenceUtil.putInt(mContext, UPDATEPROMPVERSIONCODE, Integer.valueOf(updateInfoBean.getUpdate_version_code()));
        }
        return isNeedDialog;
    }

    /**
     * 显示更新提示
     */
    public static void showDialogUpdate(Context mContext, UpdateInfo.DataBean.UpdateInfoBean updateInfoBean) {
        DialogUpdateApk dialog = new DialogUpdateApk(mContext,updateInfoBean.getUpdate_log_info(),updateInfoBean.getUpdate_apk_url(),updateInfoBean.getUpdate_type(),updateInfoBean.getUpdate_version_code());
        dialog.setCancelable(false);
        dialog.show();
    }


    /**
     * 根据用户忽略情况判断是否需要更新
     *
     * @param mContext
     * @return
     */
    private static boolean isPromptByUser(Context mContext) {
        boolean isPrompt = false;
        int updatePromptCount = getInt(mContext, UPDATEPROMPTCOUNT, 0);
        switch (updatePromptCount) {
            case 0://第一次提示 立即显示
                isPrompt = true;
                break;
            case 1://第二次提示 大于1天后提示
                if (getDayCount(mContext) >= 1) {
                    isPrompt = true;
                }
                break;
            case 2://第三次提示
                if (getDayCount(mContext) >= 3) {
                    isPrompt = true;
                }
                break;
            default://更多次数提示
                if (updatePromptCount > 0 && getDayCount(mContext) >= 7) {
                    isPrompt = true;
                }
                break;
        }
        return isPrompt;
    }

    /**
     * 初始化更新参数
     *
     * @param mContext
     */
    public static void initPromptInfo(Context mContext) {
        SharedPreferenceUtil.putInt(mContext, UPDATEPROMPTCOUNT, 0);
        SharedPreferenceUtil.putString(mContext, UPDATEPROMPTTIME, getCurrentString());
    }


    /**
     * 更新提示次数和时间
     */
    public static void updatePromptTime(Context mContext) {
        int updatePromptCount = getInt(mContext, UPDATEPROMPTCOUNT, 0);
        SharedPreferenceUtil.putInt(mContext, UPDATEPROMPTCOUNT, updatePromptCount + 1);
        SharedPreferenceUtil.putString(mContext, UPDATEPROMPTTIME, getCurrentString());
    }

    /**
     * 上次提示距离现在时间的差
     *
     * @return
     */
    public static int getDayCount(Context mContext) {
        String lastPromptTime = SharedPreferenceUtil.getString(mContext, UPDATEPROMPTTIME, getCurrentString());
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");
        String currentTime = getCurrentString();
        try {
            Date date1 = myFormat.parse(lastPromptTime);
            Date date2 = myFormat.parse(currentTime);
            long diff = date2.getTime() - date1.getTime();
            int day = (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
            return day;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 获取当前日期 20161112
     *
     * @return
     */
    private static String getCurrentString() {
        Calendar calendar = Calendar.getInstance();
        return "" + calendar.get(Calendar.YEAR)
                + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DAY_OF_MONTH);
    }





    public static void installApp(Context context , File updateFile) {
        // 核心是下面几句代码
        if (null != updateFile) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(context, "com.taptech.doufu.fileprovider", updateFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
                            Toast.makeText(context, "请在设置界面设置本应用允许安装应用", Toast.LENGTH_SHORT).show();
                            startInstallPermissionSettingActivity(context);
                            return;
                        }
                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(updateFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }

                if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    context.startActivity(intent);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void startInstallPermissionSettingActivity(Context context) {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

}

